<?php

namespace App\Services;

use App\Models\Power;
use App\Models\RolePower;
use App\Models\RoleUser;
use EasyWeChat\Kernel\Support\Arr;

class RoleService
{
    // 获取用户权限组 id
    public static function getUserRoleId($user_id)
    {
       $school_id =  request()->school_id;
       $campus_id = request()->campus_id;
       return RoleUser::where([
        'user_id' => $user_id,
        'school_id' => $school_id,
        'campus_id' => $campus_id
       ])->get()->pluck('role_id')->
       unique()->toArray();
    }

    // 创建权限树
    public static function createTree($powers)
    {

        $tree = array();
        $children = array();

        foreach ($powers as $power){
            $power->children = collect();
            if($power->parent_id == 0){
                array_push($tree, $power);
            }else {
                array_push($children, $power);
            }
        }

        foreach ($children as $child){
            RoleService::formatTree($tree, $child);
        }

        return $tree;
    }

    // 格式化权限树
    public static function formatTree($tree, $power)
    {
        foreach($tree as $item){
            if($item->id == $power->parent_id){
                $item->children->push($power);
            }else {
                if(count($item->children) > 0){
                    RoleService::formatTree($item->children, $power);
                }
            }
        }
    }

    // 通过权限组id，获取对应权限code 数组
    public static function getRoleCode($role_id)
    {
        $powerId = RolePower::
            whereIn('role_id', Arr::wrap($role_id))->
            join('power','role_power.power_id', '=', 'power.id')->
            select('role_power.*', 'power.code')->
            get()->pluck('code')->
            unique()->toArray();
        return array_values($powerId);
    }

    // 通过权限组id，获取对应权限code 数组
    public static function getAllPowerCode()
    {
        $powerId = Power::get()->pluck('code')->
            unique()->toArray();
        return array_values($powerId);
    }
}
